package com.huai.jt1078.controller;


import com.huai.jt1078.codec.AudioCodec;
import com.huai.jt1078.entity.AudioInfo;
import com.huai.jt1078.utils.SessionManager;
import com.huai.jt1078.utils.VideoUtil;
import io.netty.channel.ChannelHandlerContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileInputStream;
import java.io.InputStream;

/**
 * @author xingkong
 */
@Slf4j
@Api(tags = "测试类")
@RestController
@RequestMapping("test")
public class TetController {

    @ApiOperation("测试接口")
    @GetMapping
    public String test() {
        return "success";
    }

    @ApiOperation("测试发送音频")
    @GetMapping("/audio")
    public String sendAudio(String tag) throws Exception{
        InputStream fis = new FileInputStream("e://aaa.wav");
        ChannelHandlerContext context = SessionManager.instance.getTagChannelMap().get(tag);
        VideoUtil videoUtil = SessionManager.instance.getVideoUtils().get(tag);
        while (null == videoUtil){
            Thread.sleep(200);
            videoUtil = SessionManager.instance.getVideoUtils().get(tag);
        }
        AudioCodec audioCodec = videoUtil.getAudioCodec();
        int len = -1;
        byte[] block = new byte[320];
        byte[] head = new byte[44];

        int squeue = 0;
        int time = 0;

        String[] split = tag.split("-");

        // 去除头
        int read = fis.read(head);

        while ((len = fis.read(block)) > -1) {
            AudioInfo audioInfo = AudioInfo.builder()
                    .simNo(split[0]).channelNo(Integer.parseInt(split[1]))
                    .data(audioCodec.fromPCM(block)).loadType(6).sequence(squeue).timeStamp(time).build();
            squeue++;
//            log.info("len :{}  squeue:{} time:{}",len,squeue,time);
            time += 20;
            context.writeAndFlush(audioInfo);
            Thread.sleep(20);
        }
        return "ok";
    }
}
